package cn.zero.wechat.config;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import cn.zero.util.UtilContext;
import cn.zero.wechat.AccessTokenModel;
import cn.zero.wechat.properties.WechatProperties;
import cn.zero.wechat.req.WechatJSTicket;
import cn.zero.wechat.util.WechatUtil;

@Configuration
@EnableConfigurationProperties(WechatProperties.class)
public class WechatCommonConfig {
	
	public static String WECHAT_OAUTH2_SCOPE_BASE = "snsapi_base";
	
	public static String WECHAT_OAUTH2_SCOPE_USERINFO = "snsapi_userinfo";
	
	public static String WECHAT_AUTH_URL;
	
	public static String WECHAT_PAY_NOTIFY_URL;

	public static String WECHAT_USER_DEFAULT_PASSWORD;
	
	public static String WECHAT_TOKEN;
	
	//public static WechatConfig wechatConfig;
	
	private static WechatJSTicket wechatJSTicket;
	
	private static AccessTokenModel accessTokenModel;
	
	@Value("${wechat.token_server_url}")
	private String wechatTokenServerUrl;
	
	@Value("${wechat.user_default_password}")
	private String wechatUserDefaultPassword;
	
	@Value("${wechat.token}")
	private String wechatToken;
	
	/**
	 * 对微信相关的设置初始化
	 */
	@PostConstruct
	public void initConstruct() {
		WechatUtil.WECHAT_TOKEN_SERVER_URL = this.wechatTokenServerUrl;
		WECHAT_USER_DEFAULT_PASSWORD = wechatUserDefaultPassword;
		WECHAT_TOKEN = wechatToken;
		WechatUtil.initWechatServerConfig();
	}
	
	public static void updateAccessTokenModel(AccessTokenModel accessTokenModel) {
		WechatCommonConfig.accessTokenModel = accessTokenModel;
		WechatCommonConfig.accessTokenModel.setExpireTime(System.currentTimeMillis() + (Integer.parseInt(accessTokenModel.getExpires_in()) * 1000));
	}
	
	public static AccessTokenModel getAccessTokenModel() {
		return accessTokenModel;
	}
	
	public static void updateWechatJSTicket(WechatJSTicket wechatJSTicket) {
		WechatCommonConfig.wechatJSTicket = wechatJSTicket;
		WechatCommonConfig.wechatJSTicket.setExpireTime(System.currentTimeMillis() + (wechatJSTicket.getExpires_in() * 1000));
	}
	
	public static WechatJSTicket getWechatJSTicket() {
		return wechatJSTicket;
	}
	
	public static WechatProperties wechatConfig() {
		return UtilContext.getBean(WechatProperties.class);
	}
	
}